package tree;

public class BinaryTreeMaximumPathSum124 {
    int max = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        dfs(root);
        return max;
    }

    private int dfs(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int maxLeft = dfs(root.left);
        int maxRight = dfs(root.right);
        max = Math.max(max,root.val);
        max = Math.max(max,maxLeft+root.val);
        max = Math.max(max,maxRight+root.val);
        max = Math.max(max,maxLeft+maxRight+root.val);
        return Math.max(maxLeft,maxRight)>0?Math.max(maxLeft,maxRight)+root.val:root.val;
    }
}
